import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { setCookies, removeCookies, setStorage, removeStorage } from '@libs/storage'
import { ZTLogin } from '@/api/login'
import { goto } from '@/libs/history'
import { message } from 'antd'

export const ztLogin = createAsyncThunk(
	'user/ztLogin', // 其实就是action中的type(可以说是user子store中的login行为 写法不强制,但是讲究一点)
	async data => {
		return data // payload
		// //异步行为 接收一个函数
		// const res = await ZTLogin(data) //等待异步行为的成功
		// return res // payload
	}
)
export const logout = createAsyncThunk(
	'user/logout', // 其实就是action中的type(可以说是user子store中的login行为 写法不强制,但是讲究一点)
	async data => {
		//异步行为 接收一个函数
		// const res = await Logout(data) //等待异步行为的成功
		removeCookies()
		removeStorage('ZT_NICKNAME')
		return {} // payload
	}
)

//该store分库的初始值
const initialState = {
	token: '',
	userId: '',
	username: '',
	// 用户名称
	nickName: '测试账号',

}

export const User = createSlice({
	// store分库名称
	name: 'user',
	// store分库初始值
	initialState,
	// 处理同步
	reducers: {
		setToken: (state, action) => {
			const payload = action.payload
			state.token = payload
		},
		setUserInfo: (state, action) => {
			const payload = action.payload
			state.userInfo = payload
		},
		setDeptInfo: (state, action) => {
			const payload = action.payload
			state.deptInfo = payload
		},
	},
	// 处理异步
	extraReducers: builder => {
		// 接口请求返回
		builder.addCase(ztLogin.fulfilled, (state, { payload }) => {
			if (payload.token) {
				state.token = payload.token
				setCookies(payload.token)
			}
		})

		// 接口请求返回
		builder.addCase(logout.fulfilled, (state, { payload }) => {
			state.token = ''
			goto('/login')
		})
	}
})

// 将方法抛出
export const { setToken, setUserInfo, setDeptInfo, } = User.actions

export default User.reducer
